package com.dartfar.organize.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.dartfar.base.action.BaseAction;
import com.dartfar.base.model.Person;
import com.dartfar.base.service.PersonService;
import com.dartfar.base.vo.FunctionVo;
import com.dartfar.base.vo.TreeGridVo;
import com.dartfar.base.vo.TreeVo;
import com.dartfar.organize.model.Department;
import com.dartfar.organize.service.DepartmentService;
import com.dartfar.organize.vo.DepartmentVo;
import com.dartfar.organize.vo.OrganizeTreeVo;
import com.dartfar.util.EntityUtils;

/**
 * 部门Action对象
 * @author 王琦
 */
@Component("departmentAction")
@Scope("prototype")
public class DepartmentAction extends BaseAction {
	
	private static final long serialVersionUID = 1L;
	
	private static final Logger logger = Logger.getLogger(DepartmentAction.class);
	
	/**
	 * Service对象
	 */
	@Resource
	private DepartmentService departService;
	@Resource
	private PersonService personService;
	
	/**
	 * 页面传参
	 */
	private List<TreeGridVo> treeGridVos;
	private TreeGridVo treeGridVo;
	private DepartmentVo departVo;
	private String name;
	private String code;
	private String des;
	private String treeSign;
	private int id;
	private int parentId;	

	private List<Person> persons;

	/**
	 * 页面跳转
	 */
	public String show(){
		return "show";
	}
	
	/**
	 * 增加部门
	 */
	public String add(){
		Department depart = new Department();
		depart.setName(name);
		depart.setCode(code);
		depart.setDes(des);
		depart.setParentId(parentId);
		depart.setTreeSign(treeSign + "\\" + name);
		depart.setLeaf(true);
		departService.save(depart);
		
		//把上级部门变成非叶子节点
		Department parentDepart = departService.get(parentId);
		parentDepart.setLeaf(false);
		
		return null;
	}
	
	/**
	 *	编辑部门
	 */
	public String edit(){	
		Department depart = departService.get(id);
		//获取treeSign
		treeSign = depart.getTreeSign();
		//截取上级部门
		treeSign = treeSign.substring(0, treeSign.lastIndexOf("\\"));
		//重组treeSign
		treeSign = treeSign + "\\" + name;
		
		depart.setName(name);
		depart.setCode(code);
		depart.setDes(des);
		depart.setTreeSign(treeSign);
		departService.update(depart);		
		return null;
	}
	
	/**
	 * 删除部门
	 */
	public String delete(){
		//departService.delete(departService.get(id));
		return null;
	}
	
	
	/**
	 * 部门管理树
	 */
	public String loadDepartData(){
		logger.info("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
		try{
		List<TreeVo> lists = new ArrayList<TreeVo>(); 
		List<Department> depts = departService.getList();
		logger.info("Depts: " + depts.size());
		if(EntityUtils.isNotNull(depts) && depts.size() > 0){
			for(Department dept : depts){
				logger.info("dept: " + dept.getName());
				TreeVo treeVo = new TreeVo();
				treeVo.setId(dept.getId() + "");
				treeVo.setText(dept.getName());
				treeVo.setCode(dept.getCode());
				treeVo.setParent(dept.getParentId() + "");
				treeVo.setTreeSign(dept.getTreeSign());
				treeVo.setDes(dept.getDes());
				treeVo.setIconCls("icon-depart");
				if(!dept.isLeaf()){
					treeVo.setLeaf(dept.isLeaf());
					treeVo.setState("open");
				}else{
					treeVo.setLeaf(dept.isLeaf());
					//treeVo.setState("closed");
				}
				logger.info(treeVo + "：" + JSONObject.fromObject(treeVo).toString());
				lists.add(treeVo);
			}
			
			if(lists.size() > 0){
				TreeVo trees = departService.buildJSONTreeNode(lists);
				//toWriteObject(trees);
				//List<TreeVo> array = trees.getChildren();
				toWriteArray(trees);
			}
		}
		}catch (Exception e) {
			// TODO: handle exception
			
		}
		
		return null;
	}
	
	
	/**
	 * 通讯录树
	 * @return 全部部门树的Json字符串
	 */
	public String loadFullDeparts(){
		List<OrganizeTreeVo> organizeTreeVos = new ArrayList<OrganizeTreeVo>(); 
		List<OrganizeTreeVo> personTreeVos = new ArrayList<OrganizeTreeVo>(); 
		try{
			
			//获取根部门
			Department depart = departService.get(1);
			//获取全部人员列表
			persons = personService.getList();
			//设置根部门
			OrganizeTreeVo treeMainVo = new OrganizeTreeVo();
			treeMainVo.setId(depart.getId() + "");
			treeMainVo.setText(depart.getName());
			treeMainVo.setCode(depart.getCode());
			treeMainVo.setDes(depart.getDes());
			treeMainVo.setIconCls("icon-depart");
			//遍历人员
			personTreeVos = ergodicPersonsByDepart(depart.getId(), persons);
			
			if(!depart.isLeaf()){
				treeMainVo.setState("open");
				List<Department> subDeparts = departService.getListByParentId(depart.getId());
				List<OrganizeTreeVo> treeSubDepartVos = ergodicDepartsAddPerson(subDeparts, persons);
				
				//把子部门加入到人员下面
				for(Iterator<OrganizeTreeVo> i = treeSubDepartVos.iterator();i.hasNext();){
					personTreeVos .add(i.next());
				}
				
			}
			treeMainVo.setChildren(personTreeVos);
			organizeTreeVos.add(treeMainVo);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		

		String jsonResult = JSONArray.fromObject(organizeTreeVos).toString();
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 遍历部子门树并且增加人员树	（通讯录专用）
	 * @Param 部门列表
	 * @return 遍历部子门树并且增加人员树的Json字符串
	 */
	public List<OrganizeTreeVo> ergodicDepartsAddPerson(List<Department> departs, List<Person> persons){
		List<OrganizeTreeVo> treeGridVos = new ArrayList<OrganizeTreeVo>();
		List<OrganizeTreeVo> personTreeVos = new ArrayList<OrganizeTreeVo>();
		for(Iterator<Department> i = departs.iterator();i.hasNext();){
			Department depart = i.next();
			OrganizeTreeVo treeGridVo = new OrganizeTreeVo();
			treeGridVo.setId(depart.getId() + "");
			treeGridVo.setText(depart.getName());
			treeGridVo.setCode(depart.getCode());
			treeGridVo.setDes(depart.getDes());
			treeGridVo.setIconCls("icon-depart");
			
			//遍历人员
			personTreeVos = ergodicPersonsByDepart(depart.getId(), persons);
			
			//如果不是子结点，结点打开
			if(!depart.isLeaf()){
				treeGridVo.setState("open");
				List<Department> subDeparts = departService.getListByParentId(depart.getId());
				//遍历子部门
				List<OrganizeTreeVo> treeSubDepartVos = ergodicDepartsAddPerson(subDeparts, persons);
				
				//把子部门加入到人员下面
				for(Iterator<OrganizeTreeVo> j = treeSubDepartVos.iterator();j.hasNext();){
					personTreeVos.add(j.next());
				}
				
			}
			treeGridVo.setChildren(personTreeVos);
			treeGridVos.add(treeGridVo);
		}
		return treeGridVos;
	}
	

	/**
	 * 当前用户部门树
	 * @return 当前用户部门为根部门树的Json字符串
	 */
	public String loadCurrUserFullDeparts(){
		//主菜单VO对象
		try{
		List<OrganizeTreeVo> organizeTreeVos = new ArrayList<OrganizeTreeVo>(); 
		int cudId = curDepart().getId();
		Department depart = departService.get(cudId);
		OrganizeTreeVo treeMainVo = new OrganizeTreeVo();
		treeMainVo.setId(depart.getId() + "");
		treeMainVo.setText(depart.getName());
		treeMainVo.setCode(depart.getCode());
		treeMainVo.setDes(depart.getDes());
		treeMainVo.setIconCls("icon-depart");
		if(!depart.isLeaf()){
//			treeMainMenuVo.setState("open");
			List<Department> subDeparts = departService.getListByParentId(depart.getId());
			List<OrganizeTreeVo> treeSubDepartVos = ergodicDeparts(subDeparts);
			treeMainVo.setChildren(treeSubDepartVos);
		}
		organizeTreeVos.add(treeMainVo);

		String jsonResult = JSONArray.fromObject(organizeTreeVos).toString();
		logger.info("jsonResult: " + jsonResult);
		
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	

	/**
	 * 遍历子部门
	 * @Param 部门列表
	 * @return 遍历部子门树的Json字符串
	 */
	public List<OrganizeTreeVo> ergodicDeparts(List<Department> departs){
		List<OrganizeTreeVo> treeGridVos = new ArrayList<OrganizeTreeVo>();
		for(Iterator<Department> i = departs.iterator();i.hasNext();){
			Department depart = i.next();
			OrganizeTreeVo treeGridVo = new OrganizeTreeVo();
			treeGridVo.setId(depart.getId() + "");
			treeGridVo.setText(depart.getName());
			treeGridVo.setCode(depart.getCode());
			treeGridVo.setDes(depart.getDes());
			treeGridVo.setIconCls("icon-depart");
			//如果不是子结点，结点打开
			if(!depart.isLeaf()){
				treeGridVo.setState("open");
				List<Department> subDeparts = departService.getListByParentId(depart.getId());
				//遍历子部门
				List<OrganizeTreeVo> treeSubDepartVos = ergodicDeparts(subDeparts);
				treeGridVo.setChildren(treeSubDepartVos);
			}
			treeGridVos.add(treeGridVo);
		}
		return treeGridVos;
	}
	
	/**
	 * 根据部门ID遍历人员
	 * @Param 人员列表
	 * @return 遍历人员树的Json字符串
	 */
	public List<OrganizeTreeVo> ergodicPersonsByDepart(int departId, List<Person> persons){
		List<OrganizeTreeVo> personVos = new ArrayList<OrganizeTreeVo>();
		for (Iterator<Person> i = persons.iterator(); i.hasNext();){
			Person p = i.next();
			if(p.getDepart() != null){
				if(p.getDepart().getId() == departId){
					OrganizeTreeVo personVo = new OrganizeTreeVo();
					personVo.setId("p" + p.getId());
					personVo.setText(p.getName());
					personVo.setCode(p.getName()+"@user");
					personVo.setIconCls("icon-user");
					personVos.add(personVo);
				}
			}
		}
		return personVos;	
	}
	
	

	/**
	 * 读取树的父结点
	 * @return TreeVo的Json字符串
	 */
	public String loadTree(){
		List<Department> departs = departService.getListByParentId(0);
		//把groupList转化TreeVo对象
		List<TreeVo> treeVos = departs2Trees(departs);
		//转化为Json字符串
		String jsonResult = JSONArray.fromObject(treeVos).toString();
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 读取树的子结点
	 * @return TreeVo的Json字符串
	 */
	public String loadChildrenTree(){
		List<Department> departs = departService.getListByParentId(parentId);
		//把groupList转化TreeVo对象
		List<TreeVo> treeVos = departs2Trees(departs);
		//转化为Json字符串
		String jsonResult = JSONArray.fromObject(treeVos).toString();
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 把groupList转化TreeVo对象
	 * @param groups
	 * @return 
	 */
	private List<TreeVo> departs2Trees(List<Department> departs) {
		List<TreeVo> treeVos = new ArrayList<TreeVo>();
		for(Iterator<Department> i = departs.iterator();i.hasNext();){
			Department depart = i.next();
			TreeVo treeVo = new TreeVo();
			treeVo.setId(depart.getId()+"");
			treeVo.setText(depart.getName());
			treeVo.setIconCls("icon-root");
			if(!depart.isLeaf()){
				treeVo.setState("open");
			}
			treeVos.add(treeVo);
		}
		return treeVos;
	}
	
	

	

	/**
	 * 读取树的父列表
	 */
	public String loadTreeGrid(){		
		List<Department> departs = departService.getListByParentId(0);
		treeGridVos = departs2TreeGrids(departs);
		String jsonResult = JSONArray.fromObject(treeGridVos).toString();
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}	
	
	/**
	 * 读取树的子列表
	 */
	public String loadChildrenTreeGrid(){
		List<Department> departs = departService.getListByParentId(parentId);
		treeGridVos = departs2TreeGrids(departs);
		String jsonResult = JSONArray.fromObject(treeGridVos).toString();
		try{
			response.getWriter().write(jsonResult);
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 递归树GroupList转为TreeGridVoList对象
	 * @param groups 
	 * @param parentId 父ID
	 * @return
	 */
	public List<TreeGridVo> departs2TreeGrids(List<Department> departs, int parentId){	
		List<TreeGridVo> treeGridVos = new ArrayList<TreeGridVo>();		
		for(Iterator<Department> i = departs.iterator();i.hasNext();){
			Department depart = i.next();
			int departParentId = 0;
			if(depart.getParentId() != 0){
				departParentId = depart.getParentId();
			}
			if(parentId == departParentId){
				TreeGridVo treeGridVo = new TreeGridVo();
				treeGridVo.setId(depart.getId());
				treeGridVo.setName(depart.getName());
				treeGridVo.setIconCls("icon-depart");
				if(!depart.isLeaf()){
					//树结点为关闭
					treeGridVo.setState("closed");
					//递归下级子结点
					List<TreeGridVo> nextTreeGridVos = departs2TreeGrids(departs, depart.getId());
					treeGridVo.setChildren(nextTreeGridVos);
				}
				treeGridVos.add(treeGridVo);
			}
		}
		return treeGridVos;
	}
	
	public String test(){
		System.out.println("------------test------------");
		return SUCCESS;
	}
	

	
	//GroupList对象转TreeGridVoList对象
	public List<TreeGridVo> departs2TreeGrids(List<Department> departs){		
		List<TreeGridVo> treeGridVos = new ArrayList<TreeGridVo>();
		for(Iterator<Department> i = departs.iterator();i.hasNext();){
			Department depart = i.next();
			TreeGridVo treeGridVo = new TreeGridVo();
			treeGridVo.setId(depart.getId());
			treeGridVo.setName(depart.getName());
			treeGridVo.setIconCls("icon-depart");
			//如果不是叶子结点，结点关闭
			if(!depart.isLeaf()){
				treeGridVo.setState("closed");
			}
			treeGridVos.add(treeGridVo);
		}
		return treeGridVos;
	}


	/**
	 * Gets And Sets
	 */	
	public TreeGridVo getTreeGridVo() {
		return treeGridVo;
	}

	public void setTreeGridVo(TreeGridVo treeGridVo) {
		this.treeGridVo = treeGridVo;
	}

	public List<TreeGridVo> getTreeGridVos() {
		return treeGridVos;
	}

	public void setTreeGridVos(List<TreeGridVo> treeGridVos) {
		this.treeGridVos = treeGridVos;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getParentId() {
		return parentId;
	}

	public void setParentId(int parentId) {
		this.parentId = parentId;
	}

	public DepartmentVo getDepartVo() {
		return departVo;
	}

	public void setDepartVo(DepartmentVo departVo) {
		this.departVo = departVo;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getDes() {
		return des;
	}

	public void setDes(String des) {
		this.des = des;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public List<FunctionVo> getFunctions() {
		return functions;
	}

	public void setFunctions(List<FunctionVo> functions) {
		this.functions = functions;
	}

	public String getTreeSign() {
		return treeSign;
	}

	public void setTreeSign(String treeSign) {
		this.treeSign = treeSign;
	}

	
}
